import { GameConfig } from "../configs/GameConfig";
import { util } from "../etc/Util";
import { EnumBagItemGrid } from "../module/ItemModule";
import { PlayerOwnModel } from "./PlayerOwnModel";

@Component
export class PetModel extends PlayerOwnModel {
    static readonly MaxPetCount = EnumBagItemGrid.petEnd - EnumBagItemGrid.petStart + 1
    private static PetPrototypeGUIDTitle = '__pet_prototype'

    @mw.Property({ multicast: true, replicated: true, onChanged: 'petArrayChanged' })
    private petIDs: number[] = []

    private petGameObjects:GameObject[] = []

    protected onStart(): void {
        if(SystemUtil.isClient()){
            TimeUtil.delaySecond(2).then(()=>{
                this.petArrayChanged()
            })
        }
    }

    setPetByIndex(index:number, petID:number){
        this.petIDs[index] = petID
    }

    resetPetByIndex(index:number){
        this.petIDs[index] = 0
    }

    private petArrayChanged() {
        for(let i = 0;i < PetModel.MaxPetCount;i++){
            let petID = this.petIDs[i]
            let petGo = this.petGameObjects[i]
            // 此槽位无宠物
            if(!petID || petID == -1) {
                if(petGo){
                    GameObjPool.despawn(petGo)
                    this.petGameObjects[i] = undefined
                }
                continue
            }
            // 对比变更
            let petCfg = GameConfig.Pet.getElement(petID)
            let petPrototypeID = petGo?.[PetModel.PetPrototypeGUIDTitle]
            // 无变更
            if(petPrototypeID == petCfg.GUID) continue
            // 发生变更 清空上一个
            if(petGo) GameObjPool.despawn(petGo)
            // 生成新的
            this.petGameObjects[i] = GameObjPool.spawn(petCfg.GUID, GameObjPoolSourceType.Scene)
            // 绑定人物
            this.ownerPlayer.character.attachToSlot(this.petGameObjects[i], HumanoidSlotType.Root)
            // 设置偏移
            this.petGameObjects[i].localTransform.position = util.getCirclePosition(300, PetModel.MaxPetCount, i).add(new Vector(0,0,100))
            // 设置旋转
            this.petGameObjects[i].worldTransform.rotation = this.ownerPlayer.character.worldTransform.rotation
            // 设置原型ID
            this.petGameObjects[i][PetModel.PetPrototypeGUIDTitle] = petCfg.GUID
        }
    }
}